﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Hosting;
using Telerik.Sitefinity.GenericContent.Model;
using Telerik.Sitefinity.Modules.Blogs.Web.UI;
using Telerik.Sitefinity.Modules.Events.Web.UI;
using Telerik.Sitefinity.Modules.GenericContent;
using Telerik.Sitefinity.Modules.Libraries.Web.UI.Documents;
using Telerik.Sitefinity.Modules.Libraries.Web.UI.Images;
using Telerik.Sitefinity.Modules.News.Web.UI;
using Telerik.Sitefinity.Modules.Pages;
using Telerik.Sitefinity.Pages.Model;
using Telerik.Sitefinity.Security;
using Telerik.Sitefinity.Services.Migration;
using Telerik.Sitefinity.Security.Model;
using Telerik.Sitefinity.Modules.Lists.Web.UI;
using Telerik.Sitefinity.Model;
using Telerik.Sitefinity.Services.Search.Web.UI.Public;
using Telerik.Sitefinity.Modules.Newsletters.Web.UI.Public;
using Telerik.Sitefinity.Modules.GenericContent.Web.UI;
using System.Text;
using Telerik.Sitefinity.Web.UI.PublicControls;

namespace Migration.Classes
{
	public enum UserControlLoadState
	{
		NoErrors,
		CodeBehindError,
		AscxError
	};

	public static class MigrationControls
	{
		private static PageManager m_PageManager;
		private static ContentManager m_ContentManager;

		static MigrationControls()
		{
			m_PageManager = PageManager.GetManager();
			m_ContentManager = ContentManager.GetManager();
		}

		private static void CheckManagers()
		{
			if (m_PageManager.Provider == null)
			{
				m_PageManager = PageManager.GetManager();
			}

			if (m_ContentManager.Provider == null)
			{
				m_ContentManager = ContentManager.GetManager();
			}
		}

		public static string ParseMasterAspxAscxContent(string fileContent)
		{
			var whiteListedServerTags = new List<string>();
			whiteListedServerTags.Add("TELERIK:RADEDITOR");
			whiteListedServerTags.Add("TELERIK:RADMENU");
			whiteListedServerTags.Add("TELERIK:RADPANELBAR");
			whiteListedServerTags.Add("TELERIK:RADTABSTRIP");
			whiteListedServerTags.Add("TELERIK:RADTREEVIEW");

			// Replace the @Master tag by removing any references to C#/VB code
			Match codeFileMatch = Regex.Match(fileContent, @"<%@\s*Master.*?%>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
			if (codeFileMatch.Success)
			{
				var masterTag = codeFileMatch.Value;
				var replacedMasterTag = Regex.Replace(masterTag, @"(Inherits|Src|CodeFile)=""?[\w\._\/~-]*""?", String.Empty, RegexOptions.IgnoreCase | RegexOptions.Singleline);
				fileContent = fileContent.Replace(masterTag, String.Format("{0}{1}<%-- {2} --%>{1}", replacedMasterTag, Environment.NewLine, masterTag));
			}

			// Replace the @Control tag by removing any references to C#/VB code
			codeFileMatch = Regex.Match(fileContent, @"<%@\s*Control.*?%>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
			if (codeFileMatch.Success)
			{
				var masterTag = codeFileMatch.Value;
				var replacedControlTag = Regex.Replace(masterTag, @"(Inherits|Src|CodeFile)=""?[\w\._\/~-]*""?", String.Empty, RegexOptions.IgnoreCase | RegexOptions.Singleline);
				fileContent = fileContent.Replace(masterTag, String.Format("{0}{1}<%-- {2} --%>{1}", replacedControlTag, Environment.NewLine, masterTag));
			}

			// Comment the @Register directives that are not in the white list
			MatchCollection registerTags = Regex.Matches(fileContent, @"<%@\s*Register.*?%>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
			foreach (Match registerTag in registerTags)
			{
				var parsedRegisterTag = new ParsedRegisterTag();
				parsedRegisterTag.Retrieve(registerTag.Value);

				bool surroundWithComments = true;
				if (MigrationSettings.WhiteListedUserControlPaths.Contains(parsedRegisterTag.Src.ToUpperInvariant()))
				{
					surroundWithComments = false;
					whiteListedServerTags.Add(parsedRegisterTag.TagPrefix.ToUpperInvariant() + ":" + parsedRegisterTag.TagName.ToUpperInvariant());
				}

				if (surroundWithComments)
				{
					fileContent = fileContent.Replace(registerTag.Value, "<%-- " + registerTag.Value + " --%>");
				}
			}

			// Comment the non <asp:xxx runat="server"> tags that are not in the white list
			MatchCollection runatServerTags = Regex.Matches(fileContent, @"<(\w+):(\w+).*?runat=""?server""?", RegexOptions.IgnoreCase | RegexOptions.Singleline);
			foreach (Match runatServerTag in runatServerTags)
			{
				if (runatServerTag.Groups[1].Value.ToLowerInvariant() != "asp" && !whiteListedServerTags.Contains(runatServerTag.Groups[1].Value.ToUpperInvariant() + ":" + runatServerTag.Groups[2].Value.ToUpperInvariant()))
				{
					var replacedValue = runatServerTag.Value.Replace("runat=", "runat1=");
					fileContent = fileContent.Replace(runatServerTag.Value, replacedValue);
				}
			}

			if (Environment.MachineName == "VELKOV")
			{
				MatchCollection aspTags = Regex.Matches(fileContent, @"<%=(.*?)%>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
				foreach (Match aspTag in aspTags)
				{
					fileContent = fileContent.Replace(aspTag.Value, "<%--=" + aspTag.Groups[1].Value + "--%>");
				}
			}

			return fileContent;
		}

		public static Telerik.Sitefinity.Modules.GenericContent.Web.UI.ContentBlockBase GetContentBlock(ContentItem contentItem, bool isForTemplate)
		{
			ContentBlockBase contentBlock;
			if (isForTemplate)
			{
				contentBlock = new Telerik.Sitefinity.Modules.GenericContent.Web.UI.ContentBlockBase();
			}
			else
			{
				contentBlock = new Telerik.Sitefinity.Modules.GenericContent.Web.UI.ContentBlock();
			}
			contentBlock.ID = MigrationUtils.GetRandomId();
			contentBlock.Html = contentItem.Content;

			return contentBlock;
		}

		public static Telerik.Sitefinity.Modules.GenericContent.Web.UI.ContentBlockBase GetContentBlock(MigrationCmsGenericContent migrationControl, bool isForTemplate)
		{
			ContentBlockBase contentBlock;
			if (isForTemplate)
			{
				contentBlock = new Telerik.Sitefinity.Modules.GenericContent.Web.UI.ContentBlockBase();
			}
			else
			{
				contentBlock = new Telerik.Sitefinity.Modules.GenericContent.Web.UI.ContentBlock();
			}
			contentBlock.ID = MigrationUtils.GetRandomId();
			contentBlock.Html = migrationControl.Content;

			return contentBlock;
		}

		public static System.Web.UI.WebControls.Image GetImageControl(MigrationCmsImage migrationControl)
		{
			System.Web.UI.WebControls.Image imageControl = new System.Web.UI.WebControls.Image();
			imageControl.ImageUrl = migrationControl.ImageUrl;
			imageControl.AlternateText = migrationControl.AlternateText;

			// Save the image data to the disk
			string imageFileName = HostingEnvironment.MapPath(imageControl.ImageUrl);
			try
			{
				Directory.CreateDirectory(Path.GetDirectoryName(imageFileName));
				File.WriteAllBytes(imageFileName, migrationControl.ImageData);
			}
			catch (IOException) { }
			catch (System.Security.SecurityException) { }
			catch (UnauthorizedAccessException) { };

			return imageControl;
		}

		public static System.Web.UI.WebControls.HyperLink GetHyperLink(MigrationCmsDynamicHyperLink migrationControl)
		{
			System.Web.UI.WebControls.HyperLink hyperLink = new System.Web.UI.WebControls.HyperLink();
			hyperLink.Text = migrationControl.Text;
			hyperLink.Target = migrationControl.Target;
			hyperLink.NavigateUrl = migrationControl.NavigateUrl;

			return hyperLink;
		}

		public static BlogPostView GetBlogPostViewControl(MigrationCmsBlogPosts migrationControl)
		{
			BlogPostView blogPostView = new BlogPostView();

			return blogPostView;
		}

		public static TaxonomyControl GetTaxonomyControl()
		{
			TaxonomyControl taxonomyControl = new TaxonomyControl();

			return taxonomyControl;
		}

		public static EventsView GetEventsViewControl(MigrationCmsEventsView migrationControl)
		{
			EventsView eventsView = new EventsView();

			return eventsView;
		}

		public static NewsView GetNewsViewControl(MigrationCmsNewsView migrationControl)
		{
			NewsView newsView = new NewsView();

			return newsView;
		}

		public static ImagesView GetImagesViewControl(MigrationCmsImageGallery migrationControl)
		{
			ImagesView imagesView = new ImagesView();

			return imagesView;
		}

		public static ListView GetListViewControl(MigrationCmsListDisplay migrationControl)
		{
			ListView listView = new ListView();
			/*
			var sb = new StringBuilder();
			sb.Append("[");
			for (var i = 0; i < migrationControl.ListIds.Count; i++)
			{
				sb.AppendFormat("'{0}'", migrationControl.ListIds[i]);
				if (i + 1 < migrationControl.ListIds.Count)
					sb.AppendFormat(",");
			}
			sb.Append("]");
			listView.SelectedListIds = sb.ToString();
			*/
			return listView;
		}

		public static SubscribeForm GetSubscribeFormControl(MigrationCmsSubscriptionForm migrationControl)
		{
			SubscribeForm subscribeForm = new SubscribeForm();

			return subscribeForm;
		}

		public static SearchBox GetSearchBoxControl(MigrationCmsSearchBox migrationControl)
		{
			SearchBox searchBox = new SearchBox();

			return searchBox;
		}

		public static DownloadListView GetDownloadListViewControl(MigrationCmsDownloadList migrationControl)
		{
			DownloadListView downloadListView = new DownloadListView();

			return downloadListView;
		}

		public static void AddPermissionForEveryone<CT>(IList<CT> controls, PageManager pageManager) where CT : ControlData
		{
			CheckManagers();

			foreach (var control in controls)
			{
				var permissionsForEveryoneToViewFrontendPages = pageManager.Provider.CreatePermission(SecurityConstants.Sets.Controls.SetName, control.Id, SecurityManager.ApplicationRoles["Everyone"].Id);
				permissionsForEveryoneToViewFrontendPages.GrantActions(true, SecurityConstants.Sets.Controls.View);
				control.Permissions.Add(permissionsForEveryoneToViewFrontendPages);
			}
		}

		public static void AddPermissionsToControl(ControlData control)
		{
			bool isLayoutControl = control.IsLayoutControl;
			string permSet = isLayoutControl ? SecurityConstants.Sets.LayoutElement.SetName : SecurityConstants.Sets.Controls.SetName;

			string[] actionsAllowedForEveryone =
				isLayoutControl
				? new string[] { SecurityConstants.Sets.LayoutElement.View }
				: new string[] { SecurityConstants.Sets.Controls.View };
			Telerik.Sitefinity.Security.Model.Permission permissionForEveryone = m_PageManager.CreatePermission(permSet, ((ISecuredObject)control).Id, SecurityManager.ApplicationRoles["Everyone"].Id);
			permissionForEveryone.GrantActions(true, actionsAllowedForEveryone);

			string[] actionsAllowedForBackendUsers =
				isLayoutControl
				? new string[] { SecurityConstants.Sets.LayoutElement.Move, SecurityConstants.Sets.LayoutElement.EditProperties, SecurityConstants.Sets.LayoutElement.Delete }
				: new string[] { SecurityConstants.Sets.Controls.Move, SecurityConstants.Sets.Controls.EditProperties, SecurityConstants.Sets.Controls.Delete };
			Telerik.Sitefinity.Security.Model.Permission permissionForBackendUsers = m_PageManager.CreatePermission(permSet, ((ISecuredObject)control).Id, SecurityManager.ApplicationRoles["BackendUsers"].Id);
			permissionForBackendUsers.GrantActions(true, actionsAllowedForBackendUsers);

			string[] actionsAllowedForOwners =
				isLayoutControl
				? new string[] { SecurityConstants.Sets.LayoutElement.ChangePermissions }
				: new string[] { SecurityConstants.Sets.Controls.ChangePermissions };
			Telerik.Sitefinity.Security.Model.Permission permissionForOwners = m_PageManager.CreatePermission(permSet, ((ISecuredObject)control).Id, SecurityManager.OwnerRole.Id);
			permissionForOwners.GrantActions(true, actionsAllowedForOwners);

			((ISecuredObject)control).Permissions.Add(permissionForEveryone);
			((ISecuredObject)control).Permissions.Add(permissionForBackendUsers);
			((ISecuredObject)control).Permissions.Add(permissionForOwners);
		}

		public static string InsertControlToCollection<CT>(IList<CT> controls, MigrationCmsWebControl migrationControl, bool isForTemplate) where CT : ControlData
		{
			CheckManagers();

			if (migrationControl.IsAscx)
			{
				var ascxControl = migrationControl as MigrationCmsAscxControl;

				string fullPath = HttpContext.Current.Server.MapPath(ascxControl.AscxFilePath);
				if (!File.Exists(fullPath))
				{
					Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
					File.WriteAllText(fullPath, ascxControl.AscxFileContent);
					if (!String.IsNullOrEmpty(ascxControl.AscxFileCondeBehindContent))
					{
						File.WriteAllText(Path.GetDirectoryName(fullPath) + "\\" + ascxControl.AscxCodeBehindFileName, ascxControl.AscxFileCondeBehindContent);
					}

					// Try to create an instance of this user control to see if it is safe to include it
					UserControlLoadState loadResult = UserControlLoadState.NoErrors;
					try
					{
						var testControl = MigrationSettings.ModulePage.LoadControl(ascxControl.AscxFilePath);
					}
					catch (HttpCompileException)
					{
						loadResult = UserControlLoadState.CodeBehindError;
					}
					catch (HttpParseException)
					{
						// HttpParseExceptions are generally OK
						loadResult = UserControlLoadState.AscxError;
					}
					catch (Exception)
					{
						loadResult = UserControlLoadState.CodeBehindError;
					}

					if (loadResult == UserControlLoadState.NoErrors)
					{
						MigrationSettings.WhiteListedUserControlPaths.Add(ascxControl.AscxFilePath.ToUpperInvariant());
					}
					else if (MigrationSettings.RewriteRegisterTags)
					{
						File.WriteAllText(fullPath, MigrationControls.ParseMasterAspxAscxContent(ascxControl.AscxFileContent));
					}
				}

				CT controlToAdd = null;
				try
				{
					controlToAdd = m_PageManager.CreateControl<CT>(ascxControl.AscxFilePath, migrationControl.ContainerId);
				}
				catch (Exception ex)
				{
					if (MigrationSettings.CreateContentBlocksOnErrors)
					{
						Telerik.Sitefinity.Modules.GenericContent.Web.UI.ContentBlock contentBlock = new Telerik.Sitefinity.Modules.GenericContent.Web.UI.ContentBlock();
						contentBlock.ID = MigrationUtils.GetRandomId();
						contentBlock.Html = String.Format("<span style=\"color:red\">Error adding {0} to placeholder {1}</span><br/>Error message: <span style=\"color:red\">{2}</span>", ascxControl.AscxFilePath, migrationControl.ContainerId, ex.Message);

						controlToAdd = m_PageManager.CreateControl<CT>(contentBlock, migrationControl.ContainerId);
					}
				}

				if (MigrationSettings.CreateContentBlocksOnErrors)
				{
					AddPermissionsToControl(controlToAdd);
					controls.Add(controlToAdd);
				}

				return String.Format("&nbsp;&nbsp;Adding Ascx control {0} to container {1}.<br/>", migrationControl.TypeName, migrationControl.ContainerId);
			}
			else if (migrationControl.ControlTypeName == "Telerik.Cms.Engine.WebControls.GenericContent")
			{
				//return String.Format("&nbsp;&nbsp;Skipping for now Generic content block to container {0}.<br/>", migrationControl.ContainerId);

				// Check if the GenericContent/Content contains a Guid - then this is the Guid of the linked generic ContentItem
				MigrationCmsGenericContent genericControl = migrationControl as MigrationCmsGenericContent;
				string contentValue = genericControl.Content;
				if (MigrationUtils.IsGuid(contentValue))
				{
					Guid tempGuid = new Guid(contentValue);
					ContentItem genericContentItem = m_ContentManager.GetItems<ContentItem>().Where(t => t.Id == tempGuid).FirstOrDefault();

					if (genericContentItem != null)
					{
						Telerik.Sitefinity.Modules.GenericContent.Web.UI.ContentBlockBase contentBlock = GetContentBlock(genericContentItem, isForTemplate);
						//contentBlock.SharedContentID = tempGuid;
						//contentBlock.ProviderName = "OpenAccessDataProvider";
						CT controlToAdd = m_PageManager.CreateControl<CT>(contentBlock, migrationControl.ContainerId);
						AddPermissionsToControl(controlToAdd);
						controls.Add(controlToAdd);
					}
					else
					{
						Telerik.Sitefinity.Modules.GenericContent.Web.UI.ContentBlockBase contentBlock = GetContentBlock(genericControl, isForTemplate);
						CT controlToAdd = m_PageManager.CreateControl<CT>(contentBlock, migrationControl.ContainerId);
						AddPermissionsToControl(controlToAdd);
						controls.Add(controlToAdd);
					}
				}
				else
				{
					Telerik.Sitefinity.Modules.GenericContent.Web.UI.ContentBlock contentBlock = new Telerik.Sitefinity.Modules.GenericContent.Web.UI.ContentBlock();

					contentValue = MigrationUrlRewriter.RewriteAlbumUrls(contentValue);
					contentBlock.ID = MigrationUtils.GetRandomId();
					contentBlock.Html = contentValue;
					CT controlToAdd = m_PageManager.CreateControl<CT>(contentBlock, migrationControl.ContainerId);
					AddPermissionsToControl(controlToAdd);
					controls.Add(controlToAdd);
				}

				return String.Format("&nbsp;&nbsp;Adding Generic content block to container {0}.<br/>", migrationControl.ContainerId);
			}
			else if (migrationControl.ControlTypeName == "System.Web.UI.WebControls.Image")
			{
				System.Web.UI.WebControls.Image imageControl = GetImageControl(migrationControl as MigrationCmsImage);
				CT controlToAdd = m_PageManager.CreateControl<CT>(imageControl, migrationControl.ContainerId);
				AddPermissionsToControl(controlToAdd);
				controls.Add(controlToAdd);

				return String.Format("&nbsp;&nbsp;Adding Image to container {0}.<br/>", migrationControl.ContainerId);
			}
			else if (migrationControl.ControlTypeName == "Telerik.Cms.Web.UI.DynamicHyperLink" ||
					 migrationControl.ControlTypeName == "System.Web.UI.WebControls.HyperLink")
			{
				System.Web.UI.WebControls.HyperLink hyperLink = GetHyperLink(migrationControl as MigrationCmsDynamicHyperLink);
				CT controlToAdd = m_PageManager.CreateControl<CT>(hyperLink, migrationControl.ContainerId);
				AddPermissionsToControl(controlToAdd);
				controls.Add(controlToAdd);

				return String.Format("&nbsp;&nbsp;Adding HyperLink to container {0}.<br/>", migrationControl.ContainerId);
			}
			else if (migrationControl.ControlTypeName == "Telerik.Blogs.WebControls.BlogPosts")
			{
				BlogPostView blogPostView = GetBlogPostViewControl(migrationControl as MigrationCmsBlogPosts);
				CT controlToAdd = m_PageManager.CreateControl<CT>(blogPostView, migrationControl.ContainerId);
				AddPermissionsToControl(controlToAdd);
				controls.Add(controlToAdd);

				return String.Format("&nbsp;&nbsp;Adding BlogPosts to container {0}.<br/>", migrationControl.ContainerId);
			}
			else if (migrationControl.ControlTypeName == "Telerik.Cms.Engine.WebControls.Categories.CategoriesList")
			{
				TaxonomyControl taxonomyControl = GetTaxonomyControl();
				CT controlToAdd = m_PageManager.CreateControl<CT>(taxonomyControl, migrationControl.ContainerId);
				AddPermissionsToControl(controlToAdd);
				controls.Add(controlToAdd);

				return String.Format("&nbsp;&nbsp;Adding TaxonomyControl to container {0}.<br/>", migrationControl.ContainerId);
			}
			else if (migrationControl.ControlTypeName == "Telerik.Events.WebControls.EventsView")
			{
				EventsView eventsView = GetEventsViewControl(migrationControl as MigrationCmsEventsView);
				CT controlToAdd = m_PageManager.CreateControl<CT>(eventsView, migrationControl.ContainerId);
				AddPermissionsToControl(controlToAdd);
				controls.Add(controlToAdd);

				return String.Format("&nbsp;&nbsp;Adding EventsView to container {0}.<br/>", migrationControl.ContainerId);
			}
			else if (migrationControl.ControlTypeName == "Telerik.News.WebControls.NewsView")
			{
				NewsView newsView = GetNewsViewControl(migrationControl as MigrationCmsNewsView);
				CT controlToAdd = m_PageManager.CreateControl<CT>(newsView, migrationControl.ContainerId);
				AddPermissionsToControl(controlToAdd);
				controls.Add(controlToAdd);

				return String.Format("&nbsp;&nbsp;Adding NewsView to container {0}.<br/>", migrationControl.ContainerId);
			}
			else if (migrationControl.ControlTypeName == "Telerik.Libraries.DownloadList")
			{
				DownloadListView downloadListView = GetDownloadListViewControl(migrationControl as MigrationCmsDownloadList);
				CT controlToAdd = m_PageManager.CreateControl<CT>(downloadListView, migrationControl.ContainerId);
				AddPermissionsToControl(controlToAdd);
				controls.Add(controlToAdd);

				return String.Format("&nbsp;&nbsp;Adding DownloadListView to container {0}.<br/>", migrationControl.ContainerId);
			}
			else if (migrationControl.ControlTypeName == "Telerik.Libraries.WebControls.ImageGallery")
			{
				ImagesView imagesView = GetImagesViewControl(migrationControl as MigrationCmsImageGallery);
				CT controlToAdd = m_PageManager.CreateControl<CT>(imagesView, migrationControl.ContainerId);
				AddPermissionsToControl(controlToAdd);
				controls.Add(controlToAdd);

				return String.Format("&nbsp;&nbsp;Adding ImagesView to container {0}.<br/>", migrationControl.ContainerId);
			}
			else if (migrationControl.ControlTypeName == "Telerik.Lists.WebControls.ListDisplay")
			{
				ListView listView = GetListViewControl(migrationControl as MigrationCmsListDisplay);
				CT controlToAdd = m_PageManager.CreateControl<CT>(listView, migrationControl.ContainerId);
				AddPermissionsToControl(controlToAdd);
				controls.Add(controlToAdd);

				return String.Format("&nbsp;&nbsp;Adding ListView to container {0}.<br/>", migrationControl.ContainerId);
			}
			else if (migrationControl.ControlTypeName == "Telerik.Notifications.Newsletters.WebControl.SubscriptionForm")
			{
				SubscribeForm subscribeForm = GetSubscribeFormControl(migrationControl as MigrationCmsSubscriptionForm);
				CT controlToAdd = m_PageManager.CreateControl<CT>(subscribeForm, migrationControl.ContainerId);
				AddPermissionsToControl(controlToAdd);
				controls.Add(controlToAdd);

				return String.Format("&nbsp;&nbsp;Adding SubscriptionForm to container {0}.<br/>", migrationControl.ContainerId);
			}
			else if (migrationControl.ControlTypeName == "Telerik.Search.WebControls.SearchBox")
			{
				SearchBox searchBox = GetSearchBoxControl(migrationControl as MigrationCmsSearchBox);
				CT controlToAdd = m_PageManager.CreateControl<CT>(searchBox, migrationControl.ContainerId);
				AddPermissionsToControl(controlToAdd);
				controls.Add(controlToAdd);

				return String.Format("&nbsp;&nbsp;Adding SearchBox to container {0}.<br/>", migrationControl.ContainerId);
			}
			else
			{
				string result;
				Telerik.Sitefinity.Modules.GenericContent.Web.UI.ContentBlock contentBlock = new Telerik.Sitefinity.Modules.GenericContent.Web.UI.ContentBlock();
				contentBlock.ID = MigrationUtils.GetRandomId();

				if (!String.IsNullOrEmpty(migrationControl.ErrorMessage))
				{
					if (MigrationSettings.CreateContentBlocksOnErrors)
					{
						contentBlock.Html = String.Format("<span style=\"color:red\">Error migrating control of type {0}</span><br/>Error message: <span style=\"color:red\">{1}</span>", migrationControl.TypeName, migrationControl.ErrorMessage);
					}
					result = String.Format("&nbsp;&nbsp;Skipping adding {0} to container {1} - Error occured:<br/>&nbsp;&nbsp;<span style=\"color:red\">{2}</span><br/>", migrationControl.TypeName, migrationControl.ContainerId, migrationControl.ErrorMessage);
				}
				else
				{
					if (MigrationSettings.CreateContentBlocksOnErrors)
					{
						contentBlock.Html = String.Format("<span style=\"color:red\">Error migrating control of type {0}</span> - not supported", migrationControl.TypeName);
					}
					result = String.Format("&nbsp;&nbsp;Skipping adding {0} to container {1} - not supported.<br/>", migrationControl.TypeName, migrationControl.ContainerId);
				}

				if (MigrationSettings.CreateContentBlocksOnErrors)
				{
					CT controlToAdd = m_PageManager.CreateControl<CT>(contentBlock, migrationControl.ContainerId);
					AddPermissionsToControl(controlToAdd);
					controls.Add(controlToAdd);
				}

				return result;
			}
		}
	}
}
